package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import com.sky.entity.AddressBook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void add(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .build();
        return addressBookMapper.list(addressBook);
    }

    @Override
    public AddressBook getDefault() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .isDefault(1)
                .build();
        List<AddressBook> list =addressBookMapper.list(addressBook);
        return list.get(0);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getById(Long id) {
//        AddressBook book = AddressBook.builder()
//                .id(id)
//                .build();
//        List<AddressBook> addressBooks = addressBookMapper.list(book);
//        AddressBook addressBook = addressBooks.get(0);
        return addressBookMapper.getById(id);
    }

    @Override
    @Transactional
    public void setDefault(Long id) {
        AddressBook addressBook1 = AddressBook.builder()
                .userId(BaseContext.getCurrentId())
                .isDefault(0)
                .build();
        addressBookMapper.update(addressBook1);
        AddressBook addressBook = AddressBook.builder()
                .id(id)
                .isDefault(1)
                .build();
        addressBookMapper.update(addressBook);
    }

    @Override
    public AddressBook getByUserId(Long userId) {
        log.info("根据userID查询地址：{}", addressBookMapper.getByUserId(userId));
        return addressBookMapper.getByUserId(userId);
    }
}
